#include"mystdio.h"
#include<unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<string.h>
#include<stdlib.h>

FILE* _fopen(const char* filename, const char* mode)
{
    int fd = -1;
    if(strcmp(mode, "w") == 0)
    {
        fd = open(filename, O_CREAT|O_TRUNC|O_WRONLY, 0666);
    }
    else if(strcmp(mode, "a") == 0)
    {
        fd = open(filename, O_CREAT|O_APPEND|O_WRONLY, 0666);
    }
    else if(strcmp(mode, "r") == 0)
    {
        fd = open(filename, O_RDONLY, 0666);
    }
    else
    {
        //不配对说明打开失败
        return NULL;
    }
    
    if(fd == -1)
    {
        return NULL;
    }

    //打开文件的时候创建FILE结构体，初始化里面的各项数据，为后面的操作做准备 
    FILE* pfile = (FILE*)malloc(sizeof(FILE));
    if(pfile == NULL)
    {
        return NULL;
    }
    pfile->fd = fd;
    pfile->flag = FLUSH_ALL;
    pfile->out_pos = 0;

    return pfile;
}

int _fwrite(FILE* pfile, const char* str, int len)
{
    //向缓冲区里面写数据其实是把str拷贝到一个outbuffer数组中
    memcpy(&pfile->outbuffer[pfile->out_pos], str, len);
    pfile->out_pos += len;

    if(pfile->flag & FLUSH_NOW)
    {
        //把缓冲区outbuffer里面的数据通过系统调用写入文件fd中
        write(pfile->fd, pfile->outbuffer, pfile->out_pos);
        //此时缓冲区的属于已经被写入文件中，所以要把长度清空重新计数
        pfile->out_pos = 0;
    }
    else if(pfile->flag & FLUSH_LINE)
    {
       if(pfile->outbuffer[pfile->out_pos-1] == '\n')
       {
            write(pfile->fd, pfile->outbuffer, pfile->out_pos);
            pfile->out_pos = 0;
       }
    }
    else if(pfile->flag & FLUSH_ALL)
    {
        if(pfile->out_pos == SIZE)
        {
            write(pfile->fd, pfile->outbuffer, pfile->out_pos);
            pfile->out_pos = 0;
        }
    }

    return len;
}

void _fflush(FILE* pfile)
{
    if(pfile -> out_pos >0)
    {
        write(pfile->fd, pfile->outbuffer, pfile->out_pos); 
        pfile->out_pos = 0;
    }
}

void _fclose(FILE* pfile)
{
    if(pfile == NULL)
    {
        return;
    }
    _fflush(pfile);
    close(pfile->fd);
    free(pfile); 
}
